﻿using MapleLeaf.Application.CookBook.Models;
using MapleLeaf.Core.Dto;
using MapleLeaf.Core.Extension;
using MapleLeaf.Model.CookBook.Organization.Entity;
using MapleLeaf.Model.CookBook.Organization.Relation;
using MapleLeaf.Service.CookBook.Models;
using MapleLeaf.Service.CookBook.Organization;
using Mapster;
using SqlSugar;
using System.Linq.Expressions;

namespace MapleLeaf.Application.CookBook
{
    /// <summary>
    /// 组织管理
    /// </summary>
    public class OrganizationClient : IApplicationClient
    {
        /// <summary>
        /// 
        /// </summary>
        private readonly SysUserService _userService;
        private readonly JobPostService _jobPostService;
        private readonly OrganizationService _organizationService;
        private readonly SysRoleService _sysRoleService;
        private readonly RoleMenuService  _roleMenuService;

        private readonly UserRoleService _userRoleService;

        public OrganizationClient(SysUserService userService,
                            JobPostService jobPostService,
                            OrganizationService organizationService,
                            SysRoleService sysRoleService,
                            RoleMenuService roleMenuService,
                            UserRoleService userRoleService)
        {
            _userService = userService;
            _jobPostService = jobPostService;
            _organizationService = organizationService;
            _sysRoleService = sysRoleService;
            _roleMenuService = roleMenuService;
            _userRoleService = userRoleService;
        }

        #region 人员
        /// <summary>
        /// 获取个人资料
        /// </summary> 
        /// <returns></returns>
        public async Task<UserProfileModel> GetUserProfileModelAsync(string account)
        {
            var model = await _userService.GetUserProfileModelAsync(account);
            return model;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task ResetPasswordAsync(List<long> ids)
        {
            await _userService.ResetPasswordAsync(ids);
        }
        /// <summary>
        /// 获取人员列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<UserEntity>> GetUserListAsync(Expression<Func<UserEntity, bool>>? whereExp = null)
        {
            List<UserEntity>? list;
            if (whereExp == null)
            {
                list = await _userService.GetAllListAsync();
            }
            else
            {
                list = await _userService.GetListAsync(whereExp);
            }
            return list;
        }
        /// <summary>
        /// 获取人员列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<UserEntity>> GetUserListByOrgIdAsync(long orgId)
        {
            var res = await _userService.GetListAsync(p => p.DeptId == orgId);
            return res;
        }
        /// <summary>
        /// 获取人员列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<UserEntity>> GetUserListByOrgIdAsync(List<long> orgIds)
        {
            var res = await _userService.GetListAsync(p => orgIds.Contains(p.DeptId ?? 0));
            return res;
        }
        /// <summary>
        /// 获取人员列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<UserEntity>> GetUserListByIdAsync(List<long> ids)
        {
            var res = await _userService.GetListAsync(p => ids.Contains(p.Id));
            return res;
        }
        /// <summary>
        /// 获取人员列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<UserVo>> GetUserPageListAsync(Expression<Func<UserEntity, bool>> whereExp, PageModel pagination)
        {
            var list = new List<UserVo>();
            List<UserEntity> res = await _userService.GetPageListAsync(whereExp, pagination, p => p.CreateTime, OrderByType.Desc);
            if (res.None())
            {
                return list;
            }
            var deptIds = res.Select(p => p.DeptId).Distinct().ToList();
            var deptList = await _organizationService.GetListAsync(p => deptIds.Contains(p.Id));
            foreach (var item in res)
            {
                var dept = deptList.FirstOrDefault(p => p.Id == item.DeptId);
                var userVo = item.Adapt<UserVo>();
                userVo.DeptName = dept?.Name;
                list.Add(userVo);
            }
            return list;
        }
        /// <summary>
        /// 获取人员信息
        /// </summary>
        /// <returns></returns>
        public async Task<UserEntity> GetUserByIdAsync(long? id)
        {
            var res = new UserEntity();
            if (id != null)
            {
                res = await _userService.GetByIdAsync(id);
            }
            return res;
        }
        /// <summary>
        /// 获取人员
        /// </summary>
        /// <returns></returns>
        public async Task<UserEntity> GetUserByAccountAsync(string acount)
        {
            var res = await _userService.GetEntityByAsync(p => p.UserName == acount);
            return res;
        }

        /// <summary>
        /// 保存人员
        /// </summary>
        /// <returns></returns>
        public async Task<bool> SaveUserAsync(UserEntity entity)
        {
            bool res;
            if (entity.Id == 0)
            {
                res = await _userService.InsertAsync(entity);
            }
            else
            {
                res = await _userService.UpdateAsync(entity);
            }
            return res;
        }
        /// <summary>
        /// 删除人员
        /// </summary>
        /// <returns></returns>
        public async Task<int> DeleteUserAsync(List<long> ids)
        {
            var res = await _userService.DeleteByIdAsync(ids);
            return res;
        }
        /// <summary>
        /// 更新人员状态
        /// </summary>
        /// <returns></returns>
        public async Task<int> UpdateUserStatusAsync(List<long> ids, int status)
        {
            var res = await _userService.UpdateStatusAsync(ids, status);
            return res;
        }
        #endregion
        #region 岗位
        /// <summary>
        /// 获取岗位列表
        /// </summary>
        /// <returns></returns>
        public async Task<PaginationModel<JobPostEntity>> GetJobPostPageListAsync(Expression<Func<JobPostEntity, bool>> whereExp, PaginationModel pagination)
        {
            var page = pagination.Adapt<PaginationModel<JobPostEntity>>();
            RefAsync<int> total = 0;
            List<JobPostEntity> res = await _jobPostService.GetPageListAsync(whereExp, page.PageIndex, page.PageSize, total);
            page.Total = total;
            page.List = res;
            return page;
        }
        /// <summary>
        /// 获取岗位列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<JobPostEntity>> GetJobPostListAsync(Expression<Func<JobPostEntity, bool>> whereExp)
        {
            List<JobPostEntity> res = await _jobPostService.GetListAsync(whereExp);
            return res;
        }
        /// <summary>
        /// 获取岗位列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<JobPostEntity>> GetJobPostListAsync(List<long> ids)
        {
            List<JobPostEntity> res = await _jobPostService.GetListAsync(p => ids.Contains(p.Id));
            return res;
        }
        /// <summary>
        /// 获取岗位
        /// </summary>
        /// <returns></returns>
        public async Task<JobPostEntity> GetJobPostAsync(long id)
        {
            var res = await _jobPostService.GetByIdAsync(id);
            return res;
        }
        /// <summary>
        /// 保存岗位
        /// </summary>
        /// <returns></returns>
        public async Task<bool> SaveJobPostAsync(JobPostEntity jobPostEntity)
        {
            bool res;
            if (jobPostEntity.Id == 0)
            {
                jobPostEntity.Code = CodeHandler.GetBusinessCode("GW");
                res = await _jobPostService.InsertAsync(jobPostEntity);
            }
            else
            {
                res = await _jobPostService.UpdateAsync(jobPostEntity);
            }
            return res;
        }
        /// <summary>
        /// 删除岗位
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<bool> DeleteJobPostAsync(List<long> ids)
        {
            var res = await _jobPostService.DeleteByIdAsync(ids);
            return res > 0;
        }
        /// <summary>
        /// 更新岗位状态
        /// </summary>
        /// <returns></returns>
        public async Task<int> UpdateJobPostStatusAsync(List<long> ids, int status)
        {
            var res = await _jobPostService.UpdateStatusAsync(ids, status);
            return res;
        }
        #endregion
        #region 部门
        /// <summary>
        /// 获取部门列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<DepartmentEntity>> GetDepartmentListAsync(Expression<Func<DepartmentEntity, bool>>? whereExp = null)
        {
            List<DepartmentEntity> res;
            if (whereExp == null)
            {
                res = await _organizationService.GetAllListAsync();
            }
            else
            {
                res = await _organizationService.GetListAsync(whereExp);
            }
            res = [.. res.OrderBy(p => p.Sort)];
            return res;
        }
        /// <summary>
        /// 获取部门列表
        /// </summary>
        /// <returns></returns>
        public async Task<PaginationModel<DepartmentEntity>> GetDepartmentPageListAsync(Expression<Func<DepartmentEntity, bool>> whereExp, PaginationModel pagination)
        {
            var page = pagination.Adapt<PaginationModel<DepartmentEntity>>();
            RefAsync<int> total = 0;
            List<DepartmentEntity> res = await _organizationService.GetPageListAsync(whereExp, page.PageIndex, page.PageSize, total);
            page.Total = total;
            page.List = res;
            return page;
        }
        /// <summary>
        /// 获取部门
        /// </summary>
        /// <returns></returns>
        public async Task<List<DepartmentEntity>> GetDepartmentListAsync(List<long> ids)
        {
            var res = await _organizationService.GetListAsync(p => ids.Contains(p.Id));
            return res;
        }
        /// <summary>
        /// 获取部门
        /// </summary>
        /// <returns></returns>
        public async Task<DepartmentEntity> GetDepartmentAsync(long? id)
        {
            DepartmentEntity res = new();
            if (id > 0)
            {
                res = await _organizationService.GetByIdAsync(id);
            }
            return res;
        }

        /// <summary>
        /// 保存部门
        /// </summary>
        /// <returns></returns>
        public async Task<bool> SaveDepartmentAsync(DepartmentEntity entity)
        {
            bool res;
            if (entity.Id == 0)
            {
                res = await _organizationService.InsertAsync(entity);
            }
            else
            {
                res = await _organizationService.UpdateAsync(entity);
            }
            return res;
        }
        /// <summary>
        /// 删除部门
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<bool> DeleteDepartmentAsync(List<long> ids)
        {
            var res = await _organizationService.DeleteByIdAsync(ids);
            return res > 0;
        }
        /// <summary>
        /// 更新部门状态
        /// </summary>
        /// <returns></returns>
        public async Task<int> UpdateDepartmentStatusAsync(List<long> ids, int status)
        {
            var res = await _organizationService.UpdateStatusAsync(ids, status);
            return res;
        }
        #endregion
        #region 角色
        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<RoleEntity>> GetRoleListAsync(Expression<Func<RoleEntity, bool>> whereExp)
        {
            var res = await _sysRoleService.GetListAsync(whereExp);
            return res;
        }
        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<RoleEntity>> GetRolePageListAsync(Expression<Func<RoleEntity, bool>> whereExp, PageModel pagination)
        {
            List<RoleEntity> res = await _sysRoleService.GetPageListAsync(whereExp, pagination, p => p.Sort, OrderByType.Asc);
            return res;
        }
        /// <summary>
        /// 获取角色
        /// </summary>
        /// <returns></returns>
        public async Task<RoleEntity> GetRoleInfoAsync(long id)
        {
            var res = await _sysRoleService.GetByIdAsync(id);
            return res;
        }
        /// <summary>
        /// 获取角色-选项
        /// </summary>
        /// <returns></returns>
        public async Task<List<OptionType>> GetRoleOptionsAsync()
        {
            var res = await _sysRoleService.GetAllListAsync();

            var list = res?.OrderBy(p => p.Id).Select(p => new OptionType { Label = p.Name, Value = p.Id }).ToList() ?? [];
            return list;
        }
        /// <summary>
        /// 保存角色
        /// </summary>
        /// <returns></returns>
        public async Task<long> SaveRoleAsync(RoleEntity entity)
        {
            long res;
            if (entity.Id == 0)
            {
                var data = await _sysRoleService.InsertReturnEntityAsync(entity);
                res = data.Id;
            }
            else
            {
                await _sysRoleService.UpdateAsync(entity);
                res = entity.Id;
            }
            return res;
        }
        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<bool> DeleteRoleAsync(List<long> ids)
        {
            var res = await _sysRoleService.DeleteByIdAsync(ids);
            return res > 0;
        }
        /// <summary>
        /// 更新角色状态
        /// </summary>
        /// <returns></returns>
        public async Task<int> UpdateRoleStatusAsync(List<long> ids, int status)
        {
            var res = await _sysRoleService.UpdateStatusAsync(ids, status);
            return res;
        }
        #endregion


        #region 用户-角色
        /// <summary>
        /// 
        /// </summary>
        /// <param name="roleId"></param>
        /// <param name="datas"></param>
        public async Task<bool> SaveUserRoleAsync(long roleId, List<UserRoleEntity> datas)
        {
            var list = await _userRoleService.GetListAsync(p => p.RoleId == roleId);
            if (list.Count > 0)
            {
                var ids = list.ConvertAll(x => x.Id);
                await _userRoleService.DeleteByIdAsync(ids);
            }
            datas.ForEach(p => p.RoleId = roleId);
            var res = await _userRoleService.InsertAsync(datas);
            return res > 0;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="datas"></param>
        public async Task<bool> SaveUserRoleAsync(List<UserRoleEntity> datas)
        {
            var userids = datas.Select(p => p.UserId).Distinct().ToList();
            var roleids = datas.Select(p => p.RoleId).Distinct().ToList();
            var list = await _userRoleService.GetListAsync(p => userids.Contains(p.UserId) && roleids.Contains(p.RoleId));
            if (list.Count > 0)
            {
                var ids = new List<long>();
                foreach (var item in datas)
                {
                    var m = list.FirstOrDefault(x => x.UserId == item.UserId && x.RoleId == item.RoleId);
                    if (m != null)
                    {
                        ids.Add(m.Id);
                    }
                }
                if (ids.Count > 0)
                {
                    await _userRoleService.DeleteByIdAsync(ids);
                }
            }
            var res = await _userRoleService.InsertAsync(datas);
            return res > 0;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="roleId"></param>
        public async Task<List<UserRoleEntity>> GetUserRoleListAsync(long roleId)
        {
            var list = await _userRoleService.GetListAsync(p => p.RoleId == roleId);
            return list;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="roleId"></param>
        public async Task<List<UserRoleEntity>> GetUserRoleByUserIdAsync(long userId)
        {
            var list = await _userRoleService.GetListAsync(p => p.UserId == userId);
            return list;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="roleId"></param>
        public async Task<List<UserRoleEntity>> GetUserRoleListAsync(List<long> roleIds)
        {
            var list = await _userRoleService.GetListAsync(p => roleIds.Contains(p.RoleId));
            return list;
        }
        #endregion

        #region 角色-菜单
        /// <summary>
        /// 获取角色菜单列表 - 根据角色id
        /// </summary>
        /// <param name="roleId"></param>
        public async Task<List<RoleMenuEntity>> GetRoleMenuListAsync(long roleId)
        {
            var list = await _roleMenuService.GetListAsync(p => p.RoleId == roleId);
            return list;
        }
        /// <summary>
        ///  保存角色菜单
        /// </summary>
        /// <param name="datas"></param>
        public async Task<bool> SaveRoleMenuAsync(List<RoleMenuEntity> datas)
        {
            var menuids = datas.Select(p => p.MenuId).Distinct().ToList();
            var roleids = datas.Select(p => p.RoleId).Distinct().ToList();
            var list = await _roleMenuService.GetListAsync(p => menuids.Contains(p.MenuId) && roleids.Contains(p.RoleId));
            if (list.Count > 0)
            {
                var ids = new List<long>();
                foreach (var item in datas)
                {
                    var m = list.FirstOrDefault(x => x.MenuId == item.MenuId && x.RoleId == item.RoleId);
                    if (m != null)
                    {
                        ids.Add(m.Id);
                    }
                }
                if (ids.Count > 0)
                {
                    await _roleMenuService.DeleteByIdAsync(ids);
                }
            }
            var res = await _roleMenuService.InsertAsync(datas);
            return res > 0;
        }
        #endregion
    }
}
